package com.sy.simpleegg.ui.banner.adapter

import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.sy.simpleegg.ui.banner.holder.IBaseViewHolder
import com.youth.banner.listener.OnBannerListener
import com.youth.banner.util.BannerUtils

abstract class BaseBannerAdapter<T, VH : RecyclerView.ViewHolder>(datas: MutableList<T>) :
    RecyclerView.Adapter<VH>(), IBaseViewHolder<T, VH> {
    protected var mDatas: MutableList<T> = ArrayList()
    private var mOnBannerListener: OnBannerListener<*>? = null
    var viewHolder: VH? = null
        private set
    private var increaseCount = 2

    init {
       setDatas(datas)
    }

    fun setDatas(datas: MutableList<T>) {
        if (datas == null) {
            return
        }
        datas.also { mDatas = it }
    }

    fun getData(position: Int): T {
        return mDatas[position]
    }


    override fun onBindViewHolder(holder: VH, position: Int) {
        viewHolder = holder
        val real = getRealPosition(position)
        onBindView(holder, mDatas[real], real, realCount, position)

        holder.itemView.let {
            it.setOnClickListener {
                mOnBannerListener?.OnBannerClick(mDatas[real] as Nothing?, real)
            }
        }

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
        return onCreateHolder(parent, viewType)
    }

    override fun getItemCount(): Int {
        return if (realCount > 1) realCount + increaseCount else realCount
    }

    val realCount: Int
        get() = if (mDatas == null) 0 else mDatas!!.size

    fun getRealPosition(position: Int): Int {
        return BannerUtils.getRealPosition(increaseCount == 2, position, realCount)
    }

    fun setOnBannerListener(listener: OnBannerListener<*>?) {
        mOnBannerListener = listener
    }

    fun setIncreaseCount(increaseCount: Int) {
        this.increaseCount = increaseCount
    }
}
